// src/router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import PublicActivities from '../views/PublicActivities.vue';
import PublicActivityDetail from '../views/PublicActivityDetail.vue';
import ActivityManagement from '../views/ActivityManagement.vue';

Vue.use(VueRouter);

const routes = [
  { path: '/login', name: 'login', component: LoginView },
  { path: '/', name: 'home', component: HomeView, meta: { requiresAuth: true } },
  { path: '/public-activities', name: 'public-activities', component: PublicActivities, meta: { requiresAuth: true } },
  { path: '/public-activities/:id', name: 'public-activity-detail', component: PublicActivityDetail, meta: { requiresAuth: true } },
  { path: '/activity-management', name: 'activity-management', component: ActivityManagement, meta: { requiresAdmin: true } }
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => {
  const userRole = localStorage.getItem('userRole');
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!userRole) {
      alert('请先登录');
      next('/login');
    } else {
      next();
    }
  } else if (to.matched.some(record => record.meta.requiresAdmin)) {
    if (userRole !== 'admin') {
      alert('无权限访问');
      next('/');
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;